此系列文章會同步發文到個人部落格,有興趣的讀者可以前往觀看喔。
在 E2E 測試中,不僅有選取元素,點選按鈕,常常我們也需要上傳檔案或圖片。今天要教大家在測試腳本中如何上傳圖片。
輸入 npm install --save-dev cypress-file-upload 後,在 package.json 檔可以看到 cypress-file-upload
在 cypress/command.js 中加上 import 'cypress-file-upload';
cypress 會從 fixtures 中找測試圖片,因此在 fixtures/images 放要上傳的圖片
在測試腳本主要要寫上
 const filepath = 'images/avataaars.png' //定義照片路徑
 cy.get('#uploadButton').attachFile(filepath) //上傳檔案
 cy.get('#InsertImg').click() //點選插入圖片
完整程式碼
 describe("測試鐵人賽上傳圖片", function () {
   beforeEach(()=>{
     cy.visit("https://ithelp.ithome.com.tw/");
     cy.login({ userId: "account", password: "password" });
   })
   afterEach(()=>{
     cy.get('li > a').contains("登出").click({force: true,}); //點選登出
   })
   it("點選鐵人賽發文後,應該要可以上傳圖片", function () {
     cy.get('.menu__ironman-btn').click({force: true,}); //點選鐵人賽發文
     cy.get('.group__badge--software-dev').click({force: true,}); //點選主題
     cy.get('.post-header__title').type("測試上傳圖片"); //輸入標題
     cy.get('.fa-upload').click({force: true,}); //點選上傳圖片icon
     cy.get('.upload').click({force: true,}); //點選上傳圖片
     const filepath = 'images/avataaars.png' //定義照片路徑
     cy.get('#uploadButton').attachFile(filepath) //上傳檔案
     cy.get('#InsertImg').click() //點選插入圖片
     cy.get('.save-group__btn').click({force: true,}); //點選儲存草稿
   })
 })

